/*
 * @Date         : 2024-05-20 09:39:16 星期1
 * @Author       : xut
 * @Description  :
 */
import { resolve } from "node:path"
import nodemailer from "nodemailer"
import { User } from "@prisma/client"
import pug from "pug"
import { convert } from "html-to-text"
import { envConfig } from "../config/default"

const smtp = envConfig.smtp

export class Email {
  firstName: string
  to: string
  from: string

  constructor(public user: User, public url: string) {
    this.firstName = user.name.split(" ")[0]
    this.to = user.email
    this.from = `Codevo ${envConfig.emailFrom}`
  }

  private newTransport() {
    return nodemailer.createTransport({
      ...smtp,
      auth: {
        user: smtp.user,
        pass: smtp.pass,
      },
    })
  }

  private async send(template: string, subject: string) {
    const file = resolve(__dirname, `../views/${template}.pug`)
    const html = pug.renderFile(file, {
      firstName: this.firstName,
      subject,
      url: this.url,
    })

    const mailOptions = {
      from: this.from,
      to: this.to,
      subject,
      text: convert(html),
      html,
    }

    const info = await this.newTransport().sendMail(mailOptions)
    console.log(nodemailer.getTestMessageUrl(info))
  }

  async sendVerificationCode() {
    await this.send("verificationCode", "Your account verification code")
  }
  async sendPasswordResetToken() {
    await this.send(
      "resetPassword",
      "Your password reset token (valid for only 10 minutes)"
    )
  }
}
